from Tkinter import *

import tkSimpleDialog
import tkMessageBox
from plstcontroller import IController
from plstdocument import IDocument
import string
  
class MyDialog(tkSimpleDialog.Dialog):

    def Body(self, master):
        Label(master, text="First:").grid(row=0)
        Label(master, text="Second:").grid(row=1)

        self.e1 = Entry(master)
        self.e2 = Entry(master)

        self.e1.grid(row=0, column=1)
        self.e2.grid(row=1, column=1)
        return self.e1 # initial focus

    def Apply(self):
        print self.result
        
    def Validate(self):
        try:
            first= int(self.e1.get())
            second = int(self.e2.get())
            self.result = first, second
            return 1
        except ValueError:
            tkMessageBox.showwarning(
                "Misinputing",
                "Only digitals allowed."
            )
            return 0
            

class MyView():

    def __init__(self, ctl):
        self.ct = ctl
    
    def showDialog(self):
        self.d = MyDialog(self.root, view=self)
        self.ct.HandleRequest(self, self.d.result)

    def Show(self, root):
        self.root = root
        self.rt = StringVar()
        self.rt.set("Waiting...")
        self.lb = Label(self.root, textvariable=self.rt )
        self.lb.pack()
        Button(self.root, text="Add", command=self.showDialog).pack()
        self.root.update()

    def Update(self, doc):
        self.rt.set(doc.GetResult())


class AddAdapter:

    def __init__(self, doc):
        self.doc = doc

    def HandleRequest(self, aList):
        self.doc.SetA(aList[0])
        self.doc.SetB(aList[1])
        self.doc.Flush()


class AddDoc(IDocument):

    def __init__(self):
        IDocument.__init__(self)
        self.a = 0
        self.b = 0

    def GetResult(self):
        return self.a + self.b

    def SetA(self, value):
        self.a = value

    def SetB(self, value):
        self.b = value


class MyApp(IController):

    def __init__(self):
        IController.__init__(self)
        self.addView = MyView(self)
        self.addView1 = MyView(self)
        self.addDoc = AddDoc()
        self.addAdp = AddAdapter(self.addDoc)

    def Setup(self):
        self.addDoc.AddObserver(self.addView)
        self.addDoc.AddObserver(self.addView1)
        self.Bind(self.addView, self.addAdp)
        self.Bind(self.addView1, self.addAdp)

    def Start(self):
        self.r = Tk()
        self.t = Toplevel()
        self.addView.Show(self.r)
        self.addView1.Show(self.t)
        self.r.mainloop()

    def HandleRequest(self, view, aList):
        self.viewToDoc[view].HandleRequest(aList)
        
if __name__ == '__main__':    
    app = MyApp()
    app.Setup()
    app.Start()

